<?php
/**
 * Created by PhpStorm.
 * User: 王 朋
 * Date: 2018/4/25
 * Time: 23:35
 */
namespace application\student\controller;
use application\common\controller\Base;
use think\Db;
use think\exception\HttpException;
use think\Session;
use application\common\model\Exam;
use application\common\model\ExamineeInfo;
use application\common\model\Notify;
use application\common\model\SystemConfig;
use cauliflower\Library\File\Download;
use cauliflower\Library\Exception\UploadFileException;
use cauliflower\Library\Exception\SaveDataException;

class Index extends Base
{
    public function index() {
        $sql = 'select cfe_exam.exam_name, cfe_exam.attention_matters, cfe_exam.exam_startTime, cfe_exam.exam_id, cfe_exam.status, cfe_user.user_name from cfe_exam, cfe_user where cfe_exam.exam_id in (select exam_id from cfe_examinee_info where studentName=? and studentID=?) AND cfe_exam.exam_creator_id = cfe_user.user_id';
        $exams = Db::query($sql,[Session::get('userName'),Session::get('studentID')]);
        $this->assign([
            'title' => '学生主页',
            'messageCount' => 0,
            'exams' => $exams,
        ]);
        return $this->fetch();
    }
    public function enter($ID) {
        $trueID = $ID - 124359;
        $exam = new Exam();
        $examInfo = $exam->where('exam_id',$trueID)->select()[0];
        if ($examInfo['status'] != '1') {
            $this->error("当前不在考试期间，不能进入！", $_SERVER['HTTP_REFERER']);
        }
        $clientIP = $_SERVER['REMOTE_ADDR'];
        $examinee = new ExamineeInfo();
        $examineeInfo = $examinee->where([
            'exam_id' => $trueID,
            'studentName' => Session::get('userName'),
            'studentID' => Session::get('studentID'),
        ])->select()[0];
        $otherBind = $examinee->where(['studentBindIP' => $clientIP,'isSubmit' => '1','exam_id' => $trueID])->select();
        // 当前主机已经登录其他考生且IP绑定的情况处理
        if (!empty($otherBind) && ($otherBind[0]['studentName'] != Session::get('userName') || $otherBind[0]['studentID'] != Session::get('studentID'))) {
            $this->error("该主机已有其他考生登录，如需帮助请联系监考官！",$_SERVER['HTTP_REFERER']);
        }
        if (! $examineeInfo) {
            $this->error("服务器错误！",$_SERVER['HTTP_REFERER']);
        }else {
            // 考生主机IP判断
            if ($examineeInfo['studentBindIP'] === '0.0.0.0') {
                $examinee->save(['studentBindIP' => $clientIP, 'isLockingIP' => '1'],['id' => $examineeInfo['id']]);
            }else {
                if ($examineeInfo['isLockingIP'] === '1' && $clientIP !== $examineeInfo['studentBindIP']) {
                    $this->error("考生不能私自更换电脑，如需更换电脑请联系监考官！",$_SERVER['HTTP_REFERER'],'',5);
                }else if ($examineeInfo['isLockingIP'] === '0') {
                    $examinee->save(['studentBindIP' => $clientIP, 'isLockingIP' => '1'],['id' => $examineeInfo['id']]);
                }else {}
            }
            $filePath = ROOT_PATH.'uploads'.DS.'paper'.DS.$examInfo['exam_name'].DS.$examInfo['paper_realName'];
            if (is_file($filePath)) {
                $fileSize = filesize($filePath) < 1024 * 1024 ? round(filesize($filePath) / 1024, 2)."KB" : round(filesize($filePath) / 1024 / 1024, 2)."MB";
            }else {
                $fileSize = '';
            }
            $notify = new Notify();
            $notifies = $notify->where('exam_id', $trueID)->select();
            $this->assign([
                'title' => '考试内容',
                'messageCount' => 0,
                'paperName' => $examInfo['paper_realName'],
                'examName' => $examInfo['exam_name'],
                'fileSize' => $fileSize,
                'examinee' => $examineeInfo,
                'notifies' => $notifies,
                'paperAlert' => $fileSize === '' ? 'show' : 'hidden',
                'paperInfo' => $fileSize === '' ? 'hidden' : 'show',
            ]);
            Session::set('examID',$trueID);
            return $this->fetch();
        }
    }
    public function downloadPaper($fileName,$examName) {
        $filePath = ROOT_PATH.'uploads'.DS.'paper'.DS.$examName.DS.$fileName;
        if (! Download::downloadFile($filePath,$fileName)) {
            return "<script>alert('下载失败！')</script>";
        }
    }
    public function uploadAnswerPath() {
        if(! $this->request->isPost()) {
            throw new HttpException('403');
        }else {
            $answer = $this->request->file('answer');
            $config = new SystemConfig();
            $configInfo = $config->where('system_id', '1')->select()[0];
            if (! $configInfo) {
                $this->error("服务异常！",$_SERVER['HTTP_REFERER']);
            }else {
                if ($answer->getInfo('size') < (int)$configInfo['minFileSize'] || $answer->getInfo('size') > (int)$configInfo['maxFileSize']) {
                    $this->error("上传文件大小应在{$configInfo['minFileSize']}到{$configInfo['maxFileSize']}字节之间！",$_SERVER['HTTP_REFERER']);
                }
                if (strrchr($answer->getInfo('name'), ".") == ".php") {
                    $this->error('上传文件非法！', $_SERVER['HTTP_REFERER']);
                }
            }
            if (! $answer) {
                $this->error("请确认您选择的文件！",$_SERVER['HTTP_REFERER']);
            }else {
                $newFileName = $answer->getInfo('name');
                $exam = new Exam();
                $examInfo = $exam->where('exam_id',Session::get('examID'))->select()[0];
                if ($examInfo['status'] !== '1') {
                    $this->error("当前已不在考试期间，不能上传答卷！", $_SERVER['HTTP_REFERER']);
                }
                $examinee = new ExamineeInfo();
                $examineeInfo = $examinee->where([
                    'exam_id' => Session::get('examID'),
                    'studentName' => Session::get('userName'),
                    'studentID' => Session::get('studentID'),
                ])->select()[0];
                $oldFileName = $examineeInfo['answerPath'];
                try {
                    if (! is_dir(ROOT_PATH.'uploads')) {
                        mkdir(ROOT_PATH.'uploads');
                    }
                    if (! is_dir(ROOT_PATH.'uploads'.DS.'answer')) {
                        mkdir(ROOT_PATH.'uploads'.DS.'answer');
                    }
                    if (! is_dir(ROOT_PATH.'uploads'.DS.'answer'.DS.$examInfo['exam_name'])) {
                        mkdir(ROOT_PATH.'uploads'.DS.'answer'.DS.$examInfo['exam_name']);
                    }
                    if (! is_dir(ROOT_PATH.'uploads'.DS.'answer'.DS.$examInfo['exam_name'].DS.Session::get('studentID'))) {
                        mkdir(ROOT_PATH.'uploads'.DS.'answer'.DS.$examInfo['exam_name'].DS.Session::get('studentID'));
                    }
                    $info = $answer->move(ROOT_PATH.'uploads'.DS.'answer'.DS.$examInfo['exam_name'].DS.Session::get('studentID'),$answer->getInfo('name'));
                    if (! $info) {
                        throw new UploadFileException();
                    }else {
                        unset($info);
                        if ($newFileName != $oldFileName) {
                            $result = $examinee->save(['answerPath' => $newFileName,'answerTime' => date('Y-m-d H:i:s',time()), 'isSubmit' => '1'],
                                [
                                    'exam_id' => Session::get('examID'),
                                    'studentName' => Session::get('userName'),
                                    'studentID' => Session::get('studentID'),
                                ]);
                            if (! $result) {
                                throw new SaveDataException();
                            }else {
                                if (is_file(ROOT_PATH.'uploads'.DS.'answer'.DS.$examInfo['exam_name'].DS.Session::get('studentID').DS.$oldFileName)) {
                                    unlink(ROOT_PATH.'uploads'.DS.'answer'.DS.$examInfo['exam_name'].DS.Session::get('studentID').DS.$oldFileName);
                                }
                            }
                        }else {
                            $examinee->save(['answerTime' => date('Y-m-d H:i:s',time())],
                                [
                                    'exam_id' => Session::get('examID'),
                                    'studentName' => Session::get('userName'),
                                    'studentID' => Session::get('studentID'),
                                ]);
                        }
                    }
                }catch (UploadFileException $e) {
                    $this->error("上传答案失败！", $_SERVER['HTTP_REFERER']);
                }catch (SaveDataException $e) {
                    $filePath = ROOT_PATH.'uploads'.DS.'answer'.DS.$examInfo['exam_name'].DS.Session::get('studentID').DS.$newFileName;
                    if (is_file($filePath)) {
                        unlink($filePath);
                    }
                }catch (\Exception $e) {
                    $this->error("发生未知错误！",$_SERVER['HTTP_REFERER']);
                }
            }
            $this->redirect($_SERVER['HTTP_REFERER']);
        }
    }
    public function showNotify($notify) {
        $id = round(($notify-79853) / 17);
        $notify = new Notify();
        $notifyInfo = $notify->where('notify_id', $id)->select()[0];
        if (! $notifyInfo) {
            $this->error("系统错误！", $_SERVER['HTTP_REFERER']);
        }
        $this->assign([
            'title' => '通知详情',
            'messageCount' => 0,
            'notify' => $notifyInfo,
        ]);
        return $this->fetch();
    }
}